package com.boco.fznq.login;

import android.os.Handler;
import android.widget.TextView;


import com.boco.fznq.R;

import java.lang.ref.WeakReference;

/**
 * 发送验证码的倒计时
 * <p>
 * Created by jiangcheng on 2017/7/6.
 */

public class SendSmsCodeCountDown {

    public static final int UPDATE_COUNT_VIEW = 0x112;

    public static final int DISMISS_COUNT_VIEW = 0x113;

    /**
     * 最大的倒计时数
     */
    private static final int MAX_TIME_COUNTS = 60;

    //发送验证码的按钮，采用弱引用,防止内存泄漏
    private WeakReference<TextView> mTvSend;

    /**
     * 当前的倒计时数
     */
    private int mCurrentCount;

    /**
     * 处理倒计时的handler
     */
    private CountHandler mHandler;


    public SendSmsCodeCountDown(TextView textView) {
        mTvSend = new WeakReference<>(textView);
        mHandler = new CountHandler();
    }


    public void stopCountDown() {
        mHandler.sendEmptyMessage(DISMISS_COUNT_VIEW);
    }

    public void startCountDown() {
        mCurrentCount = MAX_TIME_COUNTS;
        mHandler.sendEmptyMessage(UPDATE_COUNT_VIEW);
    }

    class CountHandler extends Handler {

        public void handleMessage(android.os.Message msg) {
            if (mTvSend.get() == null)
                return;

            switch (msg.what) {
                case UPDATE_COUNT_VIEW:
                    mTvSend.get().setEnabled(false);
                    mCurrentCount--;
                    mTvSend.get().setText("重新发送(" + mCurrentCount + ")");
                    if (mCurrentCount <= 0) {
                        sendEmptyMessage(DISMISS_COUNT_VIEW);
                    } else {
                        sendEmptyMessageDelayed(UPDATE_COUNT_VIEW, 1000);
                    }
                    break;
                case DISMISS_COUNT_VIEW://停止倒计时
                    mTvSend.get().setEnabled(true);
                    mCurrentCount = MAX_TIME_COUNTS;
                    mTvSend.get().setText(R.string.send_sms_code_text);
                    removeMessages(UPDATE_COUNT_VIEW);
                    break;
            }
        }
    }
}
